package test.writer;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.file.FlatFileItemWriter;
import org.springframework.batch.item.file.transform.LineAggregator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Component;
import test.pojo.Person;
import test.pojo.SysLog;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : example
 * @ Author: XuLeHuang
 * @ Date: 2022/8/2 15:31
 * @ Description:
 */
@Configuration
public class MyFileWriter {
    @Bean
   public FlatFileItemWriter<Person> fileItemWriter() throws Exception {
        FlatFileItemWriter<Person> personFlatFileItemWriter = new FlatFileItemWriter<>();
        String path = "D:\\资料\\sysLog.txt";
        personFlatFileItemWriter.setResource(new FileSystemResource(path));

        personFlatFileItemWriter.setLineAggregator(new LineAggregator<Person>() {
            ObjectMapper objectMapper = new ObjectMapper();
            @Override
            public String aggregate(Person person) {
                String str = null;
                try {
                    str = objectMapper.writeValueAsString(person);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
                return str;
            }
        });
        personFlatFileItemWriter.afterPropertiesSet();
        return personFlatFileItemWriter;
    }
}
